<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--应用类型-->
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <div class="left-title">
            <div class="left" />
            <div class="txt">应用类型</div>
            <div style="margin-left: auto;">
              <el-button v-hasPermi="['system:appType:add']" size="mini" type="primary" plain icon="el-icon-plus" @click="addAppType()">新增</el-button>
            </div>
          </div>
        </div>
        <div class="head-container">
          <el-input
            v-model="typeName"
            placeholder="请输入类型名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            class="flow-tree"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          >
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <div>
                <el-tooltip :content="node.label" placement="top" effect="dark" :disabled="node.label== null || node.label.length < 15">
                  <div class="treeOverHidden">{{ node.label }}</div>
                </el-tooltip>
              </div>
              <span style="text-align: right;">
                <el-button type="text" size="mini" v-show="node.label!='全部'" @click="() => addAppType(data)" icon="el-icon-edit" v-hasPermi="['system:appType:edit']"></el-button>
                <el-button type="text" size="mini" v-show="node.label!='全部'" @click="() => appTypeDelete(node, data)" icon="el-icon-delete" v-hasPermi="['system:appType:remove']"></el-button>
              </span>
            </div>
          </el-tree>
        </div>
      </el-col>
      <!--应用-->
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="应用名称" prop="appName">
            <el-input
              v-model="queryParams.appName"
              placeholder="请输入"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="应用来源" prop="appSource">
            <el-select
              v-model="queryParams.appSource"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in appSourceSelect"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:app:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:app:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="应用名称" align="center" key="appName" prop="appName" v-if="columns[0].visible" :show-overflow-tooltip="true" />
          <el-table-column label="应用编码" align="center" key="appCode" prop="appCode" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="应用来源" align="center" key="appSource" prop="appSource" v-if="columns[2].visible" width="120" >
            <template slot-scope="scope">
              <el-tag size="mini"v-show="scope.row.appSource === 1">平台应用</el-tag>
              <el-tag size="mini"v-show="scope.row.appSource === 2" type="success">第三方应用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="应用类型" align="center" key="appTypeName" prop="appTypeName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="图标" align="center" key="iconType" prop="iconType" v-if="columns[4].visible" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <appIcon :icon-type="scope.row.iconType" :app-icon="scope.row.appIcon" :active-color="scope.row.iconColor" style="margin:0 auto" />
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" key="appSort" prop="appSort" v-if="columns[5].visible" />
          <el-table-column label="描述" align="center" key="remark" prop="remark" v-if="columns[6].visible" :show-overflow-tooltip="true" />
          <el-table-column label="是否启用" align="center" key="statusFlag" v-if="columns[7].visible">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.statusFlag"
                :active-value="parseInt(2)"
                :inactive-value="parseInt(1)"
                :disabled="scope.row.isDefault === 2"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="应用地址" align="center" key="appAddress" prop="appAddress" v-if="columns[8].visible" :show-overflow-tooltip="true" />
          <el-table-column label="应用密钥" align="center" key="appSecret" prop="appSecret" v-if="columns[9].visible" :show-overflow-tooltip="true" />
          <!-- <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[10].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="160"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:app:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                :disabled="scope.row.isDefault === 2"
                v-hasPermi="['system:app:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <addOrUpdateApp ref="addOrUpdateApp" @refreshDataList="getList"></addOrUpdateApp>
    <addOrUpdateAppType ref="addOrUpdateAppType" @refreshDataList="getAppTypeTree"></addOrUpdateAppType>
  </div>
</template>

<script>
import { listAppType, getAppType, delAppType, addAppType, updateAppType } from "@/api/system/appType";
import { listApp, getApp, delApp, addApp, updateApp } from "@/api/system/app";
import { getToken } from "@/utils/auth";
import addOrUpdateApp from "./add-or-update-app";
import addOrUpdateAppType from "./add-or-update-appType";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import appIcon from './components/appIcon.vue'

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { addOrUpdateApp, addOrUpdateAppType, appIcon },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用表格数据
      appList: null,
      // 弹出层标题
      title: "",
      // 应用类型树选项
      deptOptions: [
          {
            typeCode: 0,
            typeName: '全部',
            children: []
          }
        ],
      // 应用类型名称
      typeName: undefined,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "typeName"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appName: undefined,
        appSource: undefined,
        statusFlag: undefined,
        appType: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `应用名称`, visible: true },
        { key: 1, label: `应用编码`, visible: true },
        { key: 2, label: `应用来源`, visible: true },
        { key: 3, label: `应用类型`, visible: true },
        { key: 4, label: `图标`, visible: true },
        { key: 5, label: `排序`, visible: true },
        { key: 6, label: `描述`, visible: true },
        { key: 7, label: `是否启用`, visible: true },
        { key: 8, label: `应用地址`, visible: true },
        { key: 9, label: `应用密钥`, visible: true },
        // { key: 10, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      appSourceSelect: [
        {label: "平台应用", value: "1"},
        {label: "第三方应用", value: "2"}
      ],
      openNewTagSelect: [
        {label: "否", value: "1"},
        {label: "是", value: "2"}
      ]
    };
  },
  watch: {
    // 根据名称筛选应用类型树
    typeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getAppTypeTree();
  },
  methods: {
    /** 查询应用列表 */
    getList() {
      this.loading = true;
      listApp(this.queryParams).then(response => {
        this.appList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询应用类型下拉树结构 */
    getAppTypeTree() {
      listAppType().then(response => {
        this.deptOptions[0].children = [];
        this.deptOptions[0].children = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.typeName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.appType = data.id;
      this.handleQuery();
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.statusFlag === 2 ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.appName + '"吗？').then(function() {
        return updateApp({appId: row.appId, appCode: row.appCode, statusFlag: row.statusFlag});
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.statusFlag = row.statusFlag === 1 ? 2 : 1;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.appId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    addAppType(data) {
      var id = data ? data.id : ''
      this.$refs.addOrUpdateAppType.init(id)
    },
    handleAdd() {
      this.$refs.addOrUpdateApp.init()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.appId || this.ids;
      this.$refs.addOrUpdateApp.init(id)
    },
    /** 删除按钮操作 */
    appTypeDelete(node, data) {
      this.$modal.confirm('是否确认删除"' + node.label + '" ？').then(function() {
        return delAppType(data.id);
      }).then(() => {
        this.getAppTypeTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const appIds = row.appId || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delApp(appIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/app/export', {
        ...this.queryParams
      }, `app_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .left-title{
    display: flex;
    align-items: center;
    margin-bottom: 16px;
  }
  .left {
    width: 4px;
    height: 20px;
    background-color: #1890ff;
  }
  .txt{
    color: #606266;
    font-size: 14px;
    font-weight: 700;
    line-height: 24px;
    padding-left: 12px;
    position: relative;
    &::before{
      content: '';
      position: absolute;
      width: 4px;
      height: 16px;
      background: var(--themeColor);
      left:0;
      top: 4px;
    }
  }
  .flow-tree{
    overflow:auto;
    flex:1;
    height:300px;
    >>>.el-tree-node{
      > .el-tree-node__children{
          overflow:visible !important;
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .treeOverHidden {
    width: 150px;
    float: right;
    overflow:hidden; //超出的文本隐藏
    white-space:nowrap; //溢出不换行
    text-overflow:ellipsis; //溢出用省略号显示
  }
</style>
